package com.xingxin.controller;


import com.xingxin.entity.User;
import com.xingxin.service.UserService;
import com.xingxin.utils.ResultUtils;
import com.xingxin.config.TokenTools;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 会员表 前端控制器
 * </p>
 *
 * @author mrLiu
 * @since 2021-01-08
 */
@RestController
@RequestMapping("/user")
public class UserController {
    public static final Logger logger = LoggerFactory.getLogger(UserController.class);

    @Autowired
    private UserService userService;

    @PostMapping("/login")
    @ResponseBody
    public Map<String, Object> login(@RequestBody Map<String, Object> inMap) {
        logger.info("==>UserController--login()--start,params is:{}", inMap);
        Map<String, Object> data = new HashMap<>();
        if (CollectionUtils.isEmpty(inMap)) {
            return ResultUtils.resultMap("-1", "入参为空", null);
        }
        try {
            List<User> users = userService.getBaseMapper().selectByMap(inMap);
            if (CollectionUtils.isEmpty(users)) {
                return ResultUtils.resultMap("-1", "用户名或者密码错误!", null);
            }
            if (StringUtils.equals(users.get(0).getUsername(), (String) inMap.get("username"))
                    && StringUtils.equals(users.get(0).getPassword(), (String) inMap.get("password"))) {
                data.put("user", users.get(0));
                //生成token
                data.put("token", TokenTools.sign(users.get(0).getUsername(),
                        String.valueOf(users.get(0).getUserId())));
                return ResultUtils.resultMap("0", "success", data);
            }
        } catch (Exception e) {
            logger.error("==>UserController--login()--Exception,result is:{}", e);
            return ResultUtils.resultMap("-1", "服务器异常", null);
        }
        return null;
    }
}

